! Set up variables to hold the peripheral and the characteristics
! for the battery and buzzer.
BlunoUUID$ = "88B481F0-7443-3FA2-87D1-2A14D7014E07"
DIM sensorTag AS BLEPeripheral
DIM txchar AS BLECharacteristic

! We will look for these services.
DIM services(2) AS STRING
services(1) = "180A" : ! Device Info
services(2) = "DFB0" : ! DFB0

! temperature% = 1
isConnected = 0 !NOT connected
readytoTalk =0
buzzer = 0
relay = 0
rgbled = 0
cmd$ = " "

system.clearConsole

! Start the BLE service and begin scanning for devices.
debug = 1
BLE.startBLE
DIM uuid(0) AS STRING
BLE.startScan(uuid)


! Called when a peripheral is found. If it is a RFduino, we
! initiate a connection to it and stop scanning for peripherals.
!
! Parameters:
!    time - The time when the peripheral was discovered.
!    peripheral - The peripheral that was discovered.
!    services - List of services offered by the device.
!    advertisements - Advertisements (information provided by the
!        device without the need to read a service/characteristic)
!    rssi - Received Signal Strength Indicator
!
SUB BLEDiscoveredPeripheral (time AS DOUBLE, peripheral AS BLEPeripheral, services() AS STRING, advertisements(,) AS STRING, rssi)
IF peripheral.uuid = BlunoUUID$ THEN
 sensorTag = peripheral
 BLE.connect(sensorTag)
 BLE.stopScan

 IF debug THEN PRINT "Discovered Bluno."
END IF
END SUB

! Called to report information about the connection status of the
! peripheral or to report that services have been discovered.
!
! Parameters:
!    time - The time when the information was received.
!    peripheral - The peripheral.
!    kind - The kind of call. One of
!        1 - Connection completed
!        2 - Connection failed
!        3 - Connection lost
!        4 - Services discovered
!    message - For errors, a human-readable error message.
!    err - If there was an error, the Apple error number. If there
!        was no error, this value is 0.
!
SUB BLEPeripheralInfo (time AS DOUBLE, peripheral AS BLEPeripheral, kind AS INTEGER, message AS STRING, err AS LONG)
IF kind = 1 THEN
 ! The connection was established. Look for available services.
 IF debug THEN PRINT "Connection made."
 isConnected = 1
 peripheral.discoverServices(uuid)
ELSE IF kind = 2 OR kind = 3 THEN
 IF debug THEN PRINT "Connection lost: "; kind
 isConnected = 0
 BLE.connect(sensorTag)
ELSE IF kind = 4 THEN
 ! Services were found. If it is one of the ones we are interested
 ! in, begin discovery of its characteristics.
 DIM availableServices(1) AS BLEService
   IF debug THEN PRINT "Discovering Services."
 availableServices = peripheral.services
 FOR s = 1 to UBOUND(services, 1)
   FOR a = 1 TO UBOUND(availableServices, 1)
     IF services(s) = availableServices(a).uuid THEN
! PRINT "Service "; s; " "; a; " "; services(s); " "; availableServices(a).uuid
     IF debug THEN PRINT "Discovering characteristics for "; services(s)
       peripheral.discoverCharacteristics(uuid, availableServices(a))
     END IF
   NEXT
 NEXT
END IF
END SUB

! Called to report information about a characteristic or included
! services for a service. If it is one we are interested in, start
! handling it.
!
! Parameters:
!    time - The time when the information was received.
!    peripheral - The peripheral.
!    service - The service whose characteristic or included
!        service was found.
!    kind - The kind of call. One of
!        1 - Characteristics found
!        2 - Included services found
!    message - For errors, a human-readable error message.
!    err - If there was an error, the Apple error number. If there
!        was no error, this value is 0.
!
SUB BLEServiceInfo (time AS DOUBLE, peripheral AS BLEPeripheral, service AS BLEService, kind AS INTEGER, message AS STRING, err AS LONG)
IF kind = 1 THEN
 ! Get the characteristics.
 DIM characteristics(1) AS BLECharacteristic
 characteristics = service.characteristics
 FOR i = 1 TO UBOUND(characteristics, 1)
!  PRINT "Characteristcs "; i; " "; service.uuid; " "; characteristics(i).uuid
   IF service.uuid = services(1) OR service.uuid = services(2) THEN
     ! Found the accelerometer.
     SELECT CASE characteristics(i).uuid
       CASE "2A24"
         ! read model name
         IF debug THEN PRINT "Reading Name"
         peripheral.readCharacteristic(characteristics(i))

       CASE "DFB1"
         ! read serial port
         peripheral.setNotify(characteristics(i), 1)
         IF debug THEN PRINT "Reading Serial Port and Ready to Talk"
         peripheral.readCharacteristic(characteristics(i))
         readytoTalk = 1
         txchar = characteristics(i)

       CASE "DFB2"
         ! read serial port
         IF debug THEN PRINT "Reading DTR"
         peripheral.readCharacteristic(characteristics(i))

     END SELECT
   END IF
 NEXT
 ELSE IF kind = 2 THEN
   PRINT "Included services found"
END IF
END SUB

! Called to return information from a characteristic.
!
! Parameters:
!    time - The time when the information was received.
!    peripheral - The peripheral.
!    characteristic - The characteristic whose information
!        changed.
!    kind - The kind of call. One of
!        1 - Called after a discoverDescriptors call.
!        2 - Called after a readCharacteristics call.
!        3 - Called to report status after a writeCharacteristics
!            call.
!    message - For errors, a human-readable error message.
!    err - If there was an error, the Apple error number. If there
!        was no error, this value is 0.
!
SUB BLECharacteristicInfo (time AS DOUBLE, peripheral AS BLEPeripheral, characteristic AS BLECharacteristic, kind AS INTEGER, message AS STRING, err AS LONG)
IF kind = 1 THEN
 PRINT "Called after a discoverDescriptors call."
ELSE IF kind = 2 THEN
!  PRINT characteristic.value
 DIM value(15) AS BYTE
 value = characteristic.value
!  PRINT value
!  DIM  cvalstring AS STRING
 SELECT CASE characteristic.uuid
   CASE "2A24"
     FOR i = 1 TO UBOUND(value, 1)
       cvalstring$ = cvalstring$ & CHR(value(i))
     NEXT
     !PRINT characteristic.uuid; " "; cvalstring$

   CASE "DFB1"
     FOR i = 1 TO UBOUND(value, 1)
       cvalstring$ = cvalstring$ & CHR(value(i))
     NEXT
     PRINT characteristic.uuid; " "; cvalstring$

   CASE "DFB2"
     !PRINT characteristic.uuid; " "; characteristic.value


 END SELECT
ELSE IF kind = 3 AND err <> 0 THEN
 PRINT "Error writing "; characteristic.uuid; ": ("; err; ") "; message
END IF
END SUB



! Called when the program is not busy doing anything else, this
! subroutine updates the battery level and accelerometer plots.
!
! Parameters:
!    time - The time when the call was made.
!
SUB nullEvent (time AS DOUBLE)
! If it has been more than deltaTime seconds since the
! accelerometer plot was updated, update it with the most recent
! values reported by the device.
!strTemp$ = "<TEMP>;"


IF isConnected AND readytoTalk THEN
 PRINT
 PRINT "K - Knob            T - Tempurature"
 PRINT "H - Humidity        B - Buzzer TOGGLE"
 PRINT "L - RGBLED TOGGLE    R - Relay TOGGLE"
 PRINT "Q - QUIT "
 PRINT
 INPUT "Enter a Bluno Command: "; cmd$

 SELECT CASE UCASE(cmd$)
   CASE "K"
     strTemp$ = "<KNOB>;"
     writeBluno(strTemp$)

   CASE "T"
     strTemp$ = "<TEMP>;"
     writeBluno(strTemp$)

   CASE "H"
     strTemp$ = "<HUMID>;"
     writeBluno(strTemp$)

   CASE "B"
     IF buzzer THEN
       strTemp$ = "<BUZZER>0;"
       writeBluno(strTemp$)
       buzzer = 0
     ELSE
       strTemp$ = "<BUZZER>1;"
       writeBluno(strTemp$)
       buzzer = 1
     END IF

   CASE "R"
         IF relay THEN
       strTemp$ = "<RELAY>0;"
       writeBluno(strTemp$)
       relay = 0
     ELSE
       strTemp$ = "<RELAY>1;"
       writeBluno(strTemp$)
       relay = 1
     END IF

   CASE "L"
     IF rgbled THEN
       strTemp$ = "<RGBLED>0,0,0;"
       writeBluno(strTemp$)
       rgbled = 0
     ELSE
       strTemp$ = "<RGBLED>255,255,255;"
       writeBluno(strTemp$)
       rgbled = 1
     END IF

   CASE "Q"
     BLE.disconnect(sensorTag)
     BLE.stopBLE
     PRINT "Program stopped normally."
     STOP

   CASE ELSE
   PRINT "Unknown Command"
!      INPUT "Enter a Bluno Command: "; cmd$

 END SELECT

END IF
END SUB

SUB writeBluno (strcmd$ AS STRING)
 DIM value(LEN(strcmd$)) AS BYTE
 FOR i = 1 TO UBOUND(value, 1)
   value(i) = ASC(MID(strcmd$, i, 1))
 NEXT

 sensorTag.writeCharacteristic(txchar, value)

END SUB


